<?php
/**
 * 完整购买流程演示脚本
 * 展示从商品浏览到支付成功获取CDK码的完整流程
 */

require_once 'classes/Database.php';
require_once 'classes/ProductManager.php';
require_once 'classes/OrderManager.php';
require_once 'classes/CDKManager.php';
require_once 'classes/EasyPay.php';

echo "=== CDK支付系统完整购买流程演示 ===\n\n";

try {
    $db = Database::getInstance();
    $productManager = new ProductManager();
    $orderManager = new OrderManager();
    $cdkManager = new CDKManager();
    $easyPay = new EasyPay();

    echo "1. 浏览商品列表\n";
    echo "================\n";
    $products = $productManager->getAllProducts();
    
    if (empty($products)) {
        echo "没有找到商品，请先添加商品\n";
        exit(1);
    }
    
    // 显示商品列表
    foreach ($products as $index => $product) {
        echo ($index + 1) . ". {$product['name']} - ￥{$product['price']} (库存: {$product['stock']})\n";
        echo "   描述: {$product['description']}\n\n";
    }

    // 选择第一个商品进行演示
    $selectedProduct = $products[0];
    echo "2. 选择商品: {$selectedProduct['name']}\n";
    echo "========================================\n";
    echo "商品详情:\n";
    echo "- 名称: {$selectedProduct['name']}\n";
    echo "- 价格: ￥{$selectedProduct['price']}\n";
    echo "- 库存: {$selectedProduct['stock']}\n";
    echo "- 描述: {$selectedProduct['description']}\n\n";

    echo "3. 创建订单\n";
    echo "===========\n";
    $contactInfo = "demo@example.com";
    $paymentMethod = "alipay";
    
    $order = $orderManager->createOrder(
        $selectedProduct['id'],
        $selectedProduct['price'],
        $contactInfo,
        $paymentMethod
    );
    
    if (!$order) {
        echo "订单创建失败！\n";
        exit(1);
    }
    
    echo "订单创建成功！\n";
    echo "- 订单号: {$order['order_no']}\n";
    echo "- 商品: {$selectedProduct['name']}\n";
    echo "- 金额: ￥{$selectedProduct['price']}\n";
    echo "- 联系方式: {$contactInfo}\n";
    echo "- 支付方式: {$paymentMethod}\n\n";

    echo "4. 生成支付链接\n";
    echo "===============\n";
    $paymentInfo = $easyPay->createPayment(
        $order['order_no'],
        $selectedProduct['price'],
        $paymentMethod,
        $selectedProduct['name']
    );
    
    echo "支付链接生成成功！\n";
    echo "支付链接: {$paymentInfo['payment_url']}\n\n";
    
    echo "5. 模拟支付回调（演示支付成功后的处理）\n";
    echo "====================================\n";
    
    // 模拟支付回调数据
    $mockNotifyData = [
        'pid' => '1000',
        'trade_no' => 'TEST' . time(),
        'out_trade_no' => $order['order_no'],
        'type' => $paymentMethod,
        'name' => $selectedProduct['name'],
        'money' => $selectedProduct['price'],
        'trade_status' => 'TRADE_SUCCESS',
        'sign' => 'mock_signature',
        'sign_type' => 'MD5'
    ];
    
    echo "模拟支付回调数据:\n";
    foreach ($mockNotifyData as $key => $value) {
        echo "- {$key}: {$value}\n";
    }
    echo "\n";

    echo "6. 处理支付回调\n";
    echo "===============\n";
    
    // 在实际系统中，这一步由notify.php处理
    // 这里我们直接调用处理逻辑
    $orderDetails = $orderManager->getOrderByNo($order['order_no']);
    if ($orderDetails) {
        echo "订单状态: {$orderDetails['status']}\n";
        
        if ($orderDetails['status'] == 'pending') {
            echo "订单待支付，正在处理支付成功...\n";
            
            // 模拟支付成功处理
            $orderManager->updateOrderStatus($orderDetails['id'], 'completed', $mockNotifyData['trade_no']);
            
            // 分配CDK码
            $availableCDK = $cdkManager->getAvailableCDK($selectedProduct['id']);
            if ($availableCDK) {
                $cdkManager->useCDK($availableCDK['id'], $orderDetails['id']);
                $orderManager->updateOrderCDK($orderDetails['id'], $availableCDK['cdk_code']);
                $productManager->decreaseStock($selectedProduct['id']);
                
                echo "CDK码分配成功！\n";
                echo "- CDK码: {$availableCDK['cdk_code']}\n";
                echo "- 商品库存更新: " . ($selectedProduct['stock'] - 1) . "\n";
            } else {
                echo "警告: 没有可用的CDK码\n";
            }
            
            echo "订单状态已更新为: 已完成\n";
        } else {
            echo "订单状态: {$orderDetails['status']}\n";
        }
    }
    
    echo "\n7. 查看订单详情\n";
    echo "===============\n";
    $finalOrder = $orderManager->getOrderByNo($order['order_no']);
    if ($finalOrder) {
        echo "订单详情:\n";
        echo "- 订单号: {$finalOrder['order_no']}\n";
        echo "- 商品: {$finalOrder['product_name']}\n";
        echo "- 金额: ￥{$finalOrder['total_amount']}\n";
        echo "- 状态: {$finalOrder['status']}\n";
        echo "- CDK码: " . ($finalOrder['cdk_code'] ? $finalOrder['cdk_code'] : '未分配') . "\n";
        echo "- 创建时间: {$finalOrder['created_at']}\n";
        echo "- 更新时间: {$finalOrder['updated_at']}\n";
    }

    echo "\n=== 演示完成 ===\n";
    echo "完整购买流程演示结束！\n";
    echo "在实际使用中：\n";
    echo "1. 用户在前端页面选择商品\n";
    echo "2. 系统生成订单和支付链接\n";
    echo "3. 用户完成支付\n";
    echo "4. 支付平台回调notify.php\n";
    echo "5. 系统处理回调，分配CDK码\n";
    echo "6. 用户在前端页面查看CDK码\n";

} catch (Exception $e) {
    echo "演示过程中发生错误: " . $e->getMessage() . "\n";
    echo "堆栈跟踪: " . $e->getTraceAsString() . "\n";
}
?>
